package com.example.research.service;

import com.example.research.entity.Role;
import com.example.research.entity.User;
import com.example.research.mapper.RoleMapper;
import com.example.research.mapper.UserMapper;
import com.example.research.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户服务类
 */
@Service
@Transactional
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 根据ID查询用户
     */
    public User findById(Long id) {
        return userMapper.selectById(id);
    }

    /**
     * 根据ID查询用户（兼容方法）
     */
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    /**
     * 根据用户名查询用户
     */
    public User findByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    /**
     * 查询所有用户
     */
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    /**
     * 根据角色查询用户
     */
    public List<User> findByRole(String roleName) {
        return userMapper.selectByRole(roleName);
    }

    /**
     * 创建用户
     */
    public User createUser(User user, String roleName) {
        // 检查用户名是否已存在
        if (userMapper.countByUsername(user.getUsername()) > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (user.getEmail() != null && userMapper.countByEmail(user.getEmail()) > 0) {
            throw new RuntimeException("邮箱已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置默认状态
        if (user.getStatus() == null) {
            user.setStatus(1);
        }

        // 插入用户
        userMapper.insert(user);

        // 分配角色
        if (roleName != null) {
            Role role = roleMapper.selectByRoleName(roleName);
            if (role != null) {
                userRoleMapper.insert(user.getId(), role.getId());
            }
        }

        return user;
    }

    /**
     * 更新用户信息
     */
    public User updateUser(User user) {
        User existingUser = userMapper.selectById(user.getId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查邮箱是否被其他用户使用
        if (user.getEmail() != null) {
            User userWithEmail = userMapper.selectByUsername(user.getEmail());
            if (userWithEmail != null && !userWithEmail.getId().equals(user.getId())) {
                throw new RuntimeException("邮箱已被其他用户使用");
            }
        }

        userMapper.update(user);
        return userMapper.selectById(user.getId());
    }

    /**
     * 删除用户
     */
    public void deleteUser(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 删除用户角色关联
        userRoleMapper.deleteByUserId(id);

        // 删除用户
        userMapper.deleteById(id);
    }

    /**
     * 验证用户密码
     */
    public boolean validatePassword(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            return false;
        }
        return passwordEncoder.matches(password, user.getPassword());
    }

    /**
     * 修改密码
     */
    public void changePassword(Long userId, String oldPassword, String newPassword) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }

        user.setPassword(passwordEncoder.encode(newPassword));
        userMapper.update(user);
    }

    /**
     * 为用户分配角色
     */
    public void assignRole(Long userId, String roleName) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        Role role = roleMapper.selectByRoleName(roleName);
        if (role == null) {
            throw new RuntimeException("角色不存在");
        }

        // 检查是否已有该角色
        if (userRoleMapper.countByUserIdAndRoleId(userId, role.getId()) == 0) {
            userRoleMapper.insert(userId, role.getId());
        }
    }

    /**
     * 移除用户角色
     */
    public void removeRole(Long userId, String roleName) {
        Role role = roleMapper.selectByRoleName(roleName);
        if (role != null) {
            userRoleMapper.deleteByUserIdAndRoleId(userId, role.getId());
        }
    }

    /**
     * 启用/禁用用户
     */
    public void toggleUserStatus(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        user.setStatus(user.getStatus() == 1 ? 0 : 1);
        userMapper.update(user);
    }

    /**
     * 创建用户
     */
    public User createUser(User user) {
        // 加密密码
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userMapper.insert(user);
        return user;
    }

    /**
     * 获取教师负责的学生列表
     */
    public List<User> getStudentsByTeacher(Long teacherId) {
        return userMapper.findStudentsByTeacher(teacherId);
    }

    /**
     * 分配学生给教师
     */
    public void assignStudentToTeacher(Long studentId, Long teacherId) {
        User student = userMapper.selectById(studentId);
        if (student != null) {
            student.setTeacherId(teacherId.toString());
            userMapper.update(student);
        }
    }
}
